package com.daydayup.learn;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 三个销售卖SU7，求3个销售团队总体销售额
 */
public class ThreadLocalDemoV3 {

    public static void main(String[] args) throws InterruptedException {
        MyData myData = new MyData();
        // 模拟一个银行有3个受理窗口
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try{
            // 10个顾客(请求线程),池子里面有3个受理线程,负责处理业务
            for (int i = 0; i < 10; i++) {
                int finalI = i;
                threadPool.submit(() -> {
                    try{
                        Integer beforeInt = myData.threadLocalField.get();
                        myData.add();
                        Integer afterInt = myData.threadLocalField.get();
                        System.out.println(Thread.currentThread().getName()+"\t工作窗口\t受理第:"+ finalI +"个顾客业务\tbeforeInt="+beforeInt+"\tafterInt="+afterInt);
                    } finally {
                        myData.threadLocalField.remove();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
    // 资源类
    private static class MyData{
        ThreadLocal<Integer> threadLocalField = ThreadLocal.withInitial(() -> 0);

        public void add(){
            threadLocalField.set(1+threadLocalField.get());
        }
    }
}
